package dhee.wtqshopproject.service.impl;

import dhee.wtqshopproject.dao.OrderItemMapper;
import dhee.wtqshopproject.dao.OrderMapper;
import dhee.wtqshopproject.entity.Order;
import dhee.wtqshopproject.entity.OrderDetail;
import dhee.wtqshopproject.entity.OrderItem;
import dhee.wtqshopproject.entity.SettlementResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;

    public OrderDetail getOrderDetail(Integer orderId) {
        Order order = orderMapper.selectOrderById(orderId);
        List<OrderItem> items = orderItemMapper.selectByOrderId(orderId);
        return new OrderDetail(order, items);
    }
    public SettlementResult settle(List<OrderItem> cartItems) {
        Float totalAmount = calculateTotal(cartItems);
        String orderNo = generateOrderNo(); // 生成唯一订单号
        return new SettlementResult(orderNo, totalAmount);
    }

    private Float calculateTotal(List<OrderItem> items) {
        return items.stream()
                .map(item -> item.getPrice() * item.getQuantity())
                .reduce(0f, Float::sum);
    }

    private String generateOrderNo() {
        return System.currentTimeMillis() + "" + (new Random().nextInt(900000) + 100000);
    }
}

